﻿using JustMetClient.Socket.Models;
using System;
using System.Collections.Generic;

namespace JustMetClient.Socket
{
    /// <summary>
    /// 消息格式化工具
    /// </summary>
    public class MessageFormatter
    {
        private static string BeginSign = "0203:";
        private static string EndSign = ":0302";
        private static string[] StickySign = {  ":0302\n0203:" };

        private static string Separator = "&&&";

        /// <summary>
        /// 分割消息（最大限度处理粘包和断包的情况）
        /// </summary>
        /// <param name="s"></param> 
        /// <returns></returns>
        public static List<string> SplitMessage(string s)
        {
            List<string> msgs = new List<string>();
            if (string.IsNullOrWhiteSpace(s)) return msgs;//空字符串退出处理

            int begin = s.IndexOf(BeginSign);
            int end = s.LastIndexOf(EndSign);
            //必须有开始和结束标记，否则视为消息数据不完整，拒绝处理，防止误操作
            if (begin >= 0 && end > begin)
            {
                s = s.Substring(begin, end + EndSign.Length).Trim();//格式化消息
                //根据粘包字符串分离粘包数据
                string[] slist = s.Split(StickySign, StringSplitOptions.None);
                if (slist != null)
                {
                    foreach (var item in slist)
                    {
                        string temp = item.Trim();
                        if (temp.StartsWith(BeginSign) && temp.EndsWith(EndSign))
                        {
                            msgs.Add(temp);
                        }
                        if (temp.StartsWith(BeginSign) && !temp.EndsWith(EndSign))
                        {
                            msgs.Add(temp + EndSign);
                        }
                        if (!temp.StartsWith(BeginSign) && temp.EndsWith(EndSign))
                        {
                            msgs.Add(BeginSign + temp);
                        }
                        if (!temp.StartsWith(BeginSign) && !temp.EndsWith(EndSign))
                        {
                            msgs.Add(BeginSign + temp + EndSign);
                        }
                    }
                }
            }
            return msgs;
        }
        /// <summary>
        /// 格式化指令内容为模型
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static MessageModel String2Model(string s)
        {
            //接收：0203:AUTH-2000:qwer789:0302
            MessageModel model = null;
            try
            {
                //判断文本非空，且长度大于开始和结束标记字符长度
                if (!string.IsNullOrWhiteSpace(s) && s.Length > (BeginSign.Length + EndSign.Length))
                {
                    //处理前后空格
                    s = s.Trim();
                    //判断开始标记
                    if (s.StartsWith(BeginSign))
                    {
                        //查询、判断结束标记
                        int endFlag = s.LastIndexOf(EndSign);
                        if (endFlag > BeginSign.Length)
                        {
                            string body = s.Substring(BeginSign.Length, endFlag - BeginSign.Length);
                            //查询、判断命令代码标记
                            int codeFlag = body.IndexOf(":");
                            if (codeFlag > 0)
                            {
                                //截取指令部分，并验证指令
                                string code = body.Substring(0, codeFlag);
                                MessageType type = MessageTypeDictionary.String2Type(code);
                                if (type != MessageType.空白消息类型)
                                {
                                    //截取内容部分，并验证长度
                                    string content = body.Substring(code.Length + 1);
                                    if (content.Length > 0)
                                    {
                                        //根据分隔符分离内容，并验证长度
                                        string[] values = content.Split(new[] { Separator }, StringSplitOptions.None);
                                        if (values.Length > 0)
                                        {
                                            //闯关成功，完成消息格式化
                                            model = new MessageModel()
                                            {
                                                Type = type,
                                                Original = s,
                                                Content = content,
                                                Values = values
                                            };
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            return model;
        }

        /// <summary>
        /// 通过模型创建传输指令
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        internal static string Model2String(MessageModel model)
        {
            return Model2String(model.Type, model.Account, model.Mac, model.Values);
        }
        /// <summary>
        /// 通过模型创建传输指令
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string Model2String(MessageType type, string account, string mac, params string[] values)
        {
            //发送：0203:account-mac:AUTH-1000:jklzx12:0302
            try
            {
                if (type != MessageType.空白消息类型 && values != null)
                {
                    string user = $"{account ?? ""}-{mac ?? ""}";
                    string code = MessageTypeDictionary.Type2String(type);
                    string content = string.Join(Separator, values);
                    return $"{BeginSign}{user}:{code}:{content}{EndSign}\n";
                }
            }
            catch { }
            return null;
        }


    }
}
